package cn.dai.dao;

import cn.dai.pojo.Menu;
import cn.dai.util.JdbcUtils;

import java.util.List;

/**
 * @author ArkD42
 * @file RBAC
 * @create 2020 - 06 - 13 - 19:04
 */
public class MenuDaoImpl implements MenuDao{

    @Override
    public List<Menu> queryMainMenusByRoleIdAssociate(Integer roleId) {

        final String sql = "SELECT \n" +
                "\tm.*\n" +
                "FROM\n" +
                "\t`menu` m,\n" +
                "\t`rm_map` rm\n" +
                "WHERE\n" +
                "\trm.`menu_id` = m.`m_id`\n" +
                "\tAND rm.`role_id` = ?";

        return JdbcUtils.queryToList(
                JdbcUtils.getConnection(),
                Menu.class,
                sql,
                new Object[]{roleId}
        );
    }

    @Override
    public List<Menu> querySubMenusByParentId(Integer[] parentId) {
        // 因为这里使用了IN子句 SQL语句也需要随着数组的元素个数而确定占位的个数
        int placeHolderCounts = parentId.length;

        StringBuffer incompleteSql = new StringBuffer("SELECT \n" +
                "\t*\n" +
                "FROM \n" +
                "\t`menu`\n" +
                "WHERE\n" +
                "\t`m_parent_id` IN (");

        for (int i = 0; i < placeHolderCounts; i++) {
            // 注意最后一个就不要写逗号，并且把语句补充完整
            if (i == placeHolderCounts - 1){
                incompleteSql.append("?)");
                break;
            }
            incompleteSql.append("?, ");
        }

        final String sql = incompleteSql.toString();

        return JdbcUtils.queryToList(
                JdbcUtils.getConnection(),
                Menu.class,
                sql,
                parentId
        );
    }

    @Override
    public List<Menu> queryMenusByLimit(Integer index, Integer size) {

        final String sql = "SELECT * FROM `menu` LIMIT ?, ?";

        return JdbcUtils.queryToList(
                JdbcUtils.getConnection(),
                Menu.class,
                sql,
                new Object[]{index,size}
        );
    }

    @Override
    public Long queryMenuTotals() {
        final String sql = "SELECT COUNT(1) FROM `menu`";
        return JdbcUtils.getValue(
                JdbcUtils.getConnection(),
                sql,
                null
        );
    }
}
